<?php
namespace plug;

use Firebase\JWT\JWT as JWTUtil;
use think\facade\Config;

class SUtil
{

	/**
	 * 获取IP
	 */
	static function getIP($long = false)
	{
		$cip = getenv('HTTP_CLIENT_IP');
		$xip = getenv('HTTP_X_FORWARDED_FOR');
		$rip = getenv('REMOTE_ADDR');
		$srip = @$_SERVER['REMOTE_ADDR'];
		if ($cip && strcasecmp($cip, 'unknown')) {
			$ip = $cip;
		} elseif ($xip && strcasecmp($xip, 'unknown')) {
			$ip = $xip;
		} elseif ($rip && strcasecmp($rip, 'unknown')) {
			$ip = $rip;
		} elseif ($srip && strcasecmp($srip, 'unknown')) {
			$ip = $srip;
		}
		preg_match("/[\d\.]{7,15}/", $ip, $match);
		$ip = $match[0] ? $match[0] : 'unknown';
		if ($long) {
			return sprintf("%u", ip2long($ip));
		}
		return $ip;
	}

	/**
	 * 产生随机数
	 * @param $length 产生随机数长度
	 * @param $type 返回字符串类型
	 * @param $hash  是否由前缀，默认为空. 如:$hash = 'zz-'  结果zz-823klis
	 * @return 随机字符串 $type = 0：数字+字母
	 * $type = 1：数字
	 * $type = 2：字符
	 */
	public static function random($length = 32, $type = 0, $hash = '')
	{
		if ($type == 0) {
			$chars = '23456789abcdefghijkmnpqrstuvwxyz';
		} else if ($type == 1) {
			$chars = '0123456789';
		} else if ($type == 2) {
			$chars = 'abcdefghijklmnopqrstuvwxyz';
		}
		$max = strlen($chars) - 1;
		mt_srand(( double )microtime() * 1000000);
		for ($i = 0; $i < $length; $i++) {
			$hash .= $chars [mt_rand(0, $max)];
		}
		return $hash;
	}

	//密码加密
	public static function getHashBackend($password, $pass_random)
	{
		return md5($password . SConstant::ADMINUSERKEY . $pass_random);
	}

	/**
	 * 安全过滤数据
	 *
	 * @param string $str 需要处理的字符
	 * @param string $type 返回的字符类型，支持，string,int,float,html
	 * @param maxid $default 当出现错误或无数据时默认返回值
	 * @param boolean $checkempty 强制转化为正数
	 * @return         mixed        当出现错误或无数据时默认返回值
	 */
	public static function getStr($str, $type = 'string', $default = '', $checkempty = false, $pnumber = false)
	{
		switch ($type) {
			case 'string': //字符处理
				$_str = strip_tags($str);
				$_str = str_replace("'", '&#39;', $_str);
				$_str = str_replace("\"", '&quot;', $_str);
				$_str = str_replace("\\", '', $_str);
				$_str = str_replace("\/", '', $_str);
				break;
			case 'int': //获取整形数据
				$_str = (int)$str;
				break;
			case 'float': //获浮点形数据
				$_str = (float)$str;
				break;
			case 'html': //获取HTML，防止XSS攻击
				$_str = self::reMoveXss($str);
				break;
			case 'time':
				$_str = $str ? strtotime($str) : '';
				break;
			default: //默认当做字符处理
				$_str = strip_tags($str);
				break;
		}
		if ($checkempty == true) {
			if (empty($str)) {
				header("content-type:text/html;charset=utf-8;");
				exit("非法操作！");
			}
		}
		if ($str === '' || $str === NULL) return $default;
		if ($type == "int" || $type == "float") {
			$_str = $pnumber == true ? abs($_str) : $_str;
			return $_str;
		}
		return trim($_str);
	}

	/**
	 * guid
	 * @return string
	 */
	public static function guid()
	{
		if (function_exists('com_create_guid')) {
			$uuid = com_create_guid();
		} else {
			mt_srand((double)microtime() * 10000);//optional for php 4.2.0 and up.
			$charid = strtoupper(md5(uniqid(rand(), true)));
			$hyphen = chr(45);// "-"
			$uuid = chr(123)// "{"
				. substr($charid, 0, 8) . $hyphen
				. substr($charid, 8, 4) . $hyphen
				. substr($charid, 12, 4) . $hyphen
				. substr($charid, 16, 4) . $hyphen
				. substr($charid, 20, 12)
				. chr(125);// "}"
		}
		return trim($uuid, "{}");
//        $uuid = str_replace("{","",$uuid);
//        $uuid = str_replace("}","",$uuid);
//        return $uuid;
	}

	/**
	 * 根据json web token设置的规则生成token
	 * &#64;return \think\response\Json
	 */
	public static function createjwt($data)
	{
		$data['exp'] = time()+config::get('token.expire_time'); //token过期时间
		$key = md5(config::get('token.key')); //token的签发密钥，验证token的时候需要用到
		$jwt = JWTUtil::encode($data,$key);
		return $jwt;
	}

}
?>
